import { createRouter, createWebHistory } from 'vue-router'
import LoginView from '@/views/login/LoginView.vue'
import RegisterView from '@/views/register/RegisterView.vue'
import { user } from '@/stores/user.js'

const routes = [
  {
    path: '/',
    redirect: '/auth/login'
  },
  {
    path: '/auth/login',
    name: 'Login',
    component: LoginView,
    meta: { title: '登录' }
  },
  {
    path: '/auth/register',
    name: 'Register',
    component: RegisterView,
    meta: { title: '注册' }
  },
  {
    path: '/home',
    name: 'Home',
    component: () => import('@/views/home/HomeView.vue'),
    meta: { title: '首页' }
  },
  {
    path: '/course/play/:videoName',
    name: 'CoursePlay',
    component: () => import('@/views/video/PlayView.vue'),
    meta: { title: '课程播放' }
  }, {
    path: '/course',
    name: 'CourseShow',
    component: () => import('@/views/course/CourseView.vue'),
    meta: { title: '课程中心' }
  },
  // 管理员路由 - 布局路由
  {
    path: '/admin',
    name: 'AdminLayout',
    component: () => import('@/views/admin/index.vue'),
    meta: { title: '后台管理', requiresAuth: true, requiresAdmin: true },
    children: [
      {
        path: '', // 空路径重定向到/home
        redirect: '/admin/home'
      },
      {
        path: 'home', // 管理员首页路由
        name: 'AdminHome',
        component: () => import('@/views/admin/home/index.vue'),
        meta: { title: '首页' }
      },
      {
        path: 'users',
        name: 'AdminUsers',
        component: () => import('@/views/admin/users/index.vue'),
        meta: { title: '用户管理' }
      },
      {
        path: 'courses',
        name: 'AdminCourses',
        component: () => import('@/views/admin/courses/index.vue'),
        meta: { title: '课程管理' }
      },
      {
        path: 'menus',
        name: 'AdminMenus',
        component: () => import('@/views/admin/menus/index.vue'),
        meta: { title: '菜单管理' }
      },
      {
        path: 'data',
        name: 'AdminData',
        component: () => import('@/views/admin/knowledgeData/index.vue'),
        meta: { title: '知识库管理' }
      }
    ]
  }, {
    path: '/course/:courseId',
    name: 'CourseInfo',
    component: () => import('@/views/course/CourseInfo.vue'),
    meta: { title: '课程详情' }
  }, {
    path: "/ai",
    name: "AI",
    component: () => import('@/views/ai/AiView.vue'),
    meta: { title: 'AI' }
  }, {
    path: "/ai/:sessionId",
    name: "AIChat",
    component: () => import('@/views/ai/AiView.vue'),
    meta: { title: 'AI' }
  },{
    path: "/note",
    name: "note",
    component: () => import('@/views/note/NoteList.vue'),
    meta: { title: '知识库' }
  }
]

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes
})

router.beforeEach((to, from, next) => {
  const defaultTitle = '慧心学苑';
  const pageTitle = to.meta.title || defaultTitle;
  document.title = defaultTitle + '-' + pageTitle;

  // 初始化用户 store
  const userStore = user();

  // 检查路由的权限要求，包括父路由的权限设置
  const requiresAdmin = checkIfRequiresAdmin(to);
  const requiresAuth = checkIfRequiresAuth(to);

  // 检查是否为需要管理员权限的路由
  if (requiresAdmin) {
    // 检查是否已登录
    if (!userStore.isLoggedIn || !userStore.userInfo) {
      // 未登录则重定向到登录页
      console.debug('未登录，重定向到登录页');

      return next('/auth/login');
    }
    const isAdmin = userStore.userInfo.roleId === 2;
    if (!isAdmin) {
      // 非管理员重定向到首页
      return next('/home');
    }
  }

  // 检查是否为需要登录的路由
  if (requiresAuth) {
    // 检查是否已登录
    if (!userStore.isLoggedIn || !userStore.userInfo) {
      // 未登录则重定向到登录页
      return next('/auth/login');
    }
  }

  // 登录成功后从首页重定向到管理员页面的逻辑
  if (to.path === '/home' && userStore.isLoggedIn && userStore.userInfo && userStore.userInfo.roleId === 2) {
    // 如果是管理员登录，重定向到管理员首页
    return next('/admin/home');
  }

  // 继续导航到目标路由
  next();
});

// 检查路由是否需要管理员权限（递归检查父路由）
function checkIfRequiresAdmin(route) {
  if (route.meta.requiresAdmin) {
    return true;
  }

  if (route.matched && route.matched.length > 1) {
    // 检查所有匹配的路由记录（包括父路由）
    for (const record of route.matched) {
      if (record.meta.requiresAdmin) {
        return true;
      }
    }
  }

  return false;
}

// 检查路由是否需要登录权限（递归检查父路由）
function checkIfRequiresAuth(route) {
  if (route.meta.requiresAuth) {
    return true;
  }

  if (route.matched && route.matched.length > 1) {
    // 检查所有匹配的路由记录（包括父路由）
    for (const record of route.matched) {
      if (record.meta.requiresAuth) {
        return true;
      }
    }
  }

  return false;
}
export default router